const util = require('../../../utils/util.js');
const api = require('../../../config/api.js');
var WxParse = require('../../../lib/wxParse/wxParse.js');
const moment = require('../../../lib/moment/moment.min.js');
var app = getApp();
var that;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    articleInfo: {id:0},
    zNums:0,
    isZan:false,
    showDialog: false,
    dialog: true,
    appName:'',
    poster: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    that.data.articleInfo.id = options.id;
    if (options.scene){
      that.data.articleInfo.id = decodeURIComponent(options.scene);
    }
    //详情ID
    that.setData({
      articleInfo: that.data.articleInfo,
      appName: app.globalData.appName
    });
    that.getDetail();
  },
  getDetail(){
    app.postForm(api.GetArticleDetail, { id: that.data.articleInfo.id,isAllow: true}).then(rsp => {
      var articleInfo = rsp.data;
      var content = articleInfo.content;
      articleInfo.time = moment(articleInfo.update_time*1000).format('YYYY-MM-DD HH:MM');
      that.setData({
        articleInfo: articleInfo,
        zNums: articleInfo.zan
      });
      that.readArticle(); //阅读
      WxParse.wxParse('content', 'html', content, that, 5);
    });
  },
  onShareAppMessage: function () {
    return {
      title: that.data.articleInfo.title,
      path: that.route +'?id=' + this.data.articleInfo.id
    }
  },
  onPullDownRefresh(){
    that.getDetail();
    wx.stopPullDownRefresh();
  },
  // 分享
  shareBtn: function (e) {
    if (!app.globalData.hasLogin) {
      that.setData({
        showDialog: true
      });
    } else {
      that._showPoster();
    }
  },
  readArticle(){ //阅读
    var article = that.data.articleInfo;
    app.post(api.GiveArticleRead, { id: article.id, view: article.view, isAllow: true}).then(rsp => {
    }).catch((err) => {
      console.log(err);
    });
  },
  // 点赞
  giveBtn: function (e) {
    if(that.data.isZan){
      util.confirm.modal('您已经点赞了！');
      return false;
    }
    var article = that.data.articleInfo;
    app.post(api.GiveArticleRead, { id: article.id, zan: that.data.zNums,isAllow: true}).then(rsp => {
      that.setData({ isZan: true, zNums: rsp.data.zan });
    }).catch((err) => {
      console.log(err);
    });
  },
  _showPoster() {
    var articleId = that.data.articleInfo.id;
    var scene = articleId;
    var page = 'pages/info/detail/detail';
    that.setData({
      poster: api.GetArticleShare + '?scene=' + scene + '&page=' + page + '&articleId=' + articleId +'&time='+new Date(),
      dialog: !that.data.dialog,
    });
  },
  openDialog() {
    this.setData({ showDialog: true });
  },
  closeDialog: function () {
    this.setData({ showDialog: false });
    that._showPoster();
  },
  goLogin() {
    wx.navigateTo({
      url: '/pages/auth/accLogin/login',
    })
  },
  /**
  * 页面卸载删除海报，以免造成垃圾文件暂用服务器资源
  */
  onUnload: function () {
  },
  closeShare: function () {
    that.setData({
      dialog: !that.data.dialog
    });
  },
  downLoad() {
    wx.showLoading({
      title: '图片下载中...',
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 1000);
    var imgurl = that.data.poster;
    imgurl = imgurl.substr(0, imgurl.lastIndexOf('&')) + '&abc.png';
    wx.getImageInfo({
      src: imgurl,
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.path,
          success: function (ret) {
            wx.showToast({ title: '保存图片成功' });
            //util.confirm.modal(res.path);
          },
          fail: function (ret) {
            util.toast.fail('保存图片失败');
            //util.confirm.modal(res.path);
          }
        })
      }
    })
  },
  // 点击保存图片
  savePicture: function () {
    let that = this;
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.writePhotosAlbum']) {
          that.downLoad();
        } else {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              // 用户已经同意小程序使用
              that.downLoad();
            },
            fail: function () {
              /*获取权限时点击了拒绝以后的弹窗*/
              if (wx.canIUse('button.open-type.openSetting')) {
                wx.showModal({
                  title: '温馨提示',
                  content: '您未授权，将无法正常使用保存图片或视频的功能体验，请点击重新授权进入开启授权。',
                  confirmText: '重新授权',
                  cancelText: '取消',
                  success: function (res) {
                    if (res.confirm) {
                      wx.openSetting({
                        success: function (data) {
                          if (data.authSetting["scope.writePhotosAlbum"] == true) {
                            util.toast.success('授权成功');
                            that.downLoad();
                          } else {
                            util.toast.fail('授权失败');
                          }
                        }
                      })
                    }
                  }
                })
              } else {
                wx.showModal({
                  title: '温馨提示',
                  content: '您未授权，将无法正常使用保存图片或视频的功能体验，请删除小程序重新进入。'
                })
              }
            }
          })
        }
      }
    })
  },
  refreshCode: function () {
    util.login().then((res) => {
      that.setData({
        code: wx.getStorageSync('code')
      });
    }).catch((err) => {
      console.log("未登录报异常：", err);
    });
  },
  wxLogin: function (e) {
    let phoneInfo = e.detail;
    if (phoneInfo.errMsg != "getUserInfo:ok") {
      util.toast.fail('授权失败');
      return;
    }
    phoneInfo.code = that.data.code;
    app.post(api.LoginByPhone, phoneInfo).then(rsp => {
      let res = rsp.data;
      if (!res.isSubmitAuthInfo) { //还未提交认证信息
        util.confirm.modalOk('您的信息还没有注册！');
      } else {
        //是否授权基本信息(微信头像，昵称)
        if (res.isAuthBaseInfo) {
          app.globalData.isAuthBaseInfo = true;
          app.globalData.userInfo = res.userInfo;
          wx.setStorageSync('userInfo', res.userInfo);
          wx.setStorageSync('isAuthBaseInfo', true);
        } else {
          wx.setStorageSync('isAuthBaseInfo', false);
        }
        //实名是否认证成功
        if (res.isCert) {
          app.globalData.isCert = true;
        }
        wx.setStorageSync('phoneNumber', res.phoneNumber);
        wx.setStorageSync('tenantNo', res.tenantNo);
        wx.setStorageSync('token', res.token);
        app.globalData.phoneNumber = res.phoneNumber;
        app.globalData.tenantNo = res.tenantNo;
        app.globalData.hasLogin = true;
        console.log('go into index...');
        wx.switchTab({
          url: '/pages/index/index',
        })
      }
    }).catch((err) => {
      console.log('err', err);
      that.refreshCode();
    });
  },
  wxLoginByUserInfo: function (e) {
    if (e.detail.userInfo == undefined) {
      util.toast.fail('微信授权失败');
    } else {
      util.getCheckUserInfo().then(res => {
        console.log('userInfo', res);
        wx.getStorageSync('userInfo', res.userInfo);
        app.globalData.userInfo = res.userInfo;
        res.code = that.data.code;
        app.post(api.LoginByPhone, res).then(res => {
          console.log(res)
        }).catch((err) => {
          console.log('err', err);
        });
      });

    }
  },
})